package com.siblings.loan.ui.steps.adapter

import android.graphics.Color
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.RelativeLayout
import androidx.recyclerview.widget.RecyclerView
import com.lib.base.utils.log.LogHelper
import com.siblings.lib_baseadapter.SIBRecyclerViewAdapter
import com.siblings.lib_baseadapter.SIBViewHolderHelper
import com.siblings.loan.R
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.utils.event.SibEventType
import org.json.JSONObject

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/5 13:54
 * @Annotation：认证流程步骤适配器
 */
class SibStepCommonAdapter(recyclerView: RecyclerView?): SIBRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                return R.layout.item_step_common_select
            }
            "SELECT" -> {//选择
                if (model.optString("paramName") == "gender"){//性别
                    return R.layout.item_step_common_gender
                } else {
                    return R.layout.item_step_common_select
                }

            }
            else -> {//输入框
                return R.layout.item_step_common_input
            }
        }
    }

    override fun setItemChildListener(helper: SIBViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
    }

    override fun fillData(helper: SIBViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val textTitle = helper.getTextView(R.id.textTitle)
        textTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),model.optString("title"),"*")

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                if (model.optString("paramName") == "gender"){//性别
                    showSelectGender(helper,position,model)
                } else {
                    showSelectView(helper,position,model)
                }
            }
            else -> {//输入框
                showInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showInputView(helper: SIBViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val editText = helper.getView<EditText>(R.id.editText)
        editText.setHint(hint)
        var showText = ""
        if (model.has("selectItem")){
            showText = model.optJSONObject("selectItem").optString("title")
        }
        editText.setText(showText)
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.setOnFocusChangeListener { v, hasFocus ->
            LogHelper.e(">>>>>>>>>>>>$hasFocus>>>>>>>${editText.text}")
            if (!hasFocus){
                HttpHelper.addSibEventAction(String.format(SibEventType.FORM.SIB_FORM_STEP_INPUT_XX,model.optString("paramName")),editText.text.toString())
            }
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择性别
     */
    private fun showSelectGender(helper: SIBViewHolderHelper, position: Int, model: JSONObject){
        val itemLayout1 = helper.getView<RelativeLayout>(R.id.itemLayout1)
        itemLayout1.setBackgroundResource(R.drawable.sib_radius_frame_ffeceff3_12)
        val textValue1 = helper.getTextView(R.id.textValue1)
        textValue1.setTextColor(Color.parseColor("#FF999999"))
        textValue1.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        val imgSelect1 = helper.getImageView(R.id.imgSelect1)
        imgSelect1.setImageResource(R.mipmap.pic_checkbox_normal)

        val itemLayout2 = helper.getView<RelativeLayout>(R.id.itemLayout2)
        itemLayout2.setBackgroundResource(R.drawable.sib_radius_frame_ffeceff3_12)
        val textValue2 = helper.getTextView(R.id.textValue2)
        textValue2.setTextColor(Color.parseColor("#FF999999"))
        textValue2.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
        val imgSelect2 = helper.getImageView(R.id.imgSelect2)
        imgSelect2.setImageResource(R.mipmap.pic_checkbox_normal)

        val values = model.optJSONArray("values")
        if (values != null){
            if (values.length() > 0){
                val item = values.optJSONObject(0)
                textValue1.text = item.optString("title")
            }
            if (values.length() > 1){
                val item = values.optJSONObject(1)
                textValue2.text = item.optString("title")
            }
        }

        //选中
        if (model.has("selectItem")){
            val selectValue = model.getJSONObject("selectItem")
            if (values != null){
                if (values.length() > 0){
                    val item = values.optJSONObject(0)
                    if (item.optString("title") == selectValue.optString("title")){
                        itemLayout1.setBackgroundResource(R.drawable.sib_step_gender_select)
                        textValue1.setTextColor(Color.parseColor("#FF4DB673"))
                        textValue1.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                        imgSelect1.setImageResource(R.mipmap.pic_checkbox_select)
                    }
                }
                if (values.length() > 1){
                    val item = values.optJSONObject(1)
                    if (item.optString("title") == selectValue.optString("title")){
                        itemLayout2.setBackgroundResource(R.drawable.sib_step_gender_select)
                        textValue2.setTextColor(Color.parseColor("#FF4DB673"))
                        textValue2.setTypeface(Typeface.DEFAULT,Typeface.BOLD)
                        imgSelect2.setImageResource(R.mipmap.pic_checkbox_select)
                    }
                }
            }
        } else {
            itemLayout1.setBackgroundResource(R.drawable.sib_radius_frame_ffeceff3_12)
            textValue1.setTextColor(Color.parseColor("#FF999999"))
            textValue1.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
            imgSelect1.setImageResource(R.mipmap.pic_checkbox_normal)

            itemLayout2.setBackgroundResource(R.drawable.sib_radius_frame_ffeceff3_12)
            textValue2.setTextColor(Color.parseColor("#FF999999"))
            textValue2.setTypeface(Typeface.DEFAULT,Typeface.NORMAL)
            imgSelect2.setImageResource(R.mipmap.pic_checkbox_normal)
        }

        itemLayout1.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(0)
                model.put("selectItem", item)
                HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }

        itemLayout2.setOnClickListener {
            if (values != null) {
                val item = values.optJSONObject(1)
                model.put("selectItem", item)
                HttpHelper.addSibEventAction(String.format(SibEventType.CLICK.SIB_CLICK_STEP_XX_SELECT,model.optString("paramName")),item.optString("title"))
            }
            notifyItemChanged(position)
        }
    }

    /**
     * 选择类型
     */
    private fun showSelectView(helper: SIBViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val textValue = helper.getTextView(R.id.textValue)
        textValue.setHint(hint)
        if (model.has("selectItem")){
            textValue.text = model.getJSONObject("selectItem").optString("title")
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}